package com.example.agricultural_big_data.service.serviceimpl;

import com.alibaba.fastjson.JSONObject;
import com.example.agricultural_big_data.mapper.PlantMapper;
import com.example.agricultural_big_data.mapper.UserMapper;
import com.example.agricultural_big_data.pojo.*;
import com.example.agricultural_big_data.service.UserService;

import com.example.agricultural_big_data.util.DateUtils.DateUtils;
import com.example.agricultural_big_data.util.MD5Util;
import com.example.agricultural_big_data.util.RedisUtil;
import com.example.agricultural_big_data.util.TokenUtil;
import com.example.agricultural_big_data.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ForkJoinPool;

/**
 * @author xiao yang
 * @Description:
 * @date 2021/1/3114:46
 */
@Service
public class UserServicelmpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    PlantMapper plantMapper;

    @Autowired
    Result result;

    @Autowired
    TokenUtil tokenUtil;

    @Autowired
    RedisUtil redisUtil;


    @Override
    public JSONObject register(JSONObject data) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        JSONObject jsonObject;
        String phone=data.getString("id");
        String name=data.getString("name");
        String passwd=data.getString("passwd");
        String dbpass= MD5Util.getEncryptedPwd(passwd);
        String id = UUID.randomUUID().toString().replaceAll("-","");
        User user=new User();
        user.setUserId(id);
        user.setPassword(dbpass);
        user.setUserName(name);
        user.setUserPhone(phone);
        int rs=userMapper.register(user);
        if (rs>0){
            jsonObject=result.responseResult(ResultCode.success.getStatusCode(),ResultCode.success.getMsg());
        }else{
            jsonObject=result.responseResult(ResultCode.exception.getStatusCode(),ResultCode.exception.getMsg());
        }
        return jsonObject;
    }

    @Override
    public JSONObject userLogin(JSONObject data) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        JSONObject jsonObject;
        Map<Object,Object> map=new HashMap<>();
        String name=data.getString("username");
        String password=data.getString("password");
        User user=userMapper.login(name);
        if (user != null) {
            String token = tokenUtil.createJwtToken(String.valueOf(user.getUserId()));
            redisUtil.set("token", token, 7200L);
            map.put("user", user);
            map.put("token", token);
            System.out.println("password:" + password);
            if (user == null) {
                jsonObject = result.responseResult(ResultCode.fail.getStatusCode(), ResultCode.fail.getMsg());
                return jsonObject;
            } else if (MD5Util.validPassword(password, user.getPassword())) {
                jsonObject = result.responseResult(ResultCode.success.getStatusCode(), ResultCode.success.getMsg(), map);
                return jsonObject;
            } else {
                jsonObject = result.responseResult(ResultCode.error.getStatusCode(), ResultCode.error.getMsg());
                return jsonObject;
            }
        }
        return null;
    }



    @Override
    public JSONObject masterRegister(JSONObject data) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        JSONObject jsonObject;
        String phone=data.getString("id");
        String name=data.getString("name");
        String passwd=data.getString("passwd");
        String dbpass=MD5Util.getEncryptedPwd(passwd);
        String id = UUID.randomUUID().toString().replaceAll("-","");
        User user=new User();
        user.setUserId(id);
        user.setPassword(dbpass);
        user.setUserName(name);
        user.setUserPhone(phone);
        int rs=userMapper.register(user);
        if (rs>0){
            jsonObject=result.responseResult(ResultCode.success.getStatusCode(),ResultCode.success.getMsg());
        }else{
            jsonObject=result.responseResult(ResultCode.exception.getStatusCode(),ResultCode.exception.getMsg());
        }
        return jsonObject;
    }

    @Override
    public JSONObject getInfoById(String userId) {
        JSONObject jsonObject;
        User rs = userMapper.getInfoById(userId);
        if (rs!=null){
            jsonObject=result.responseResult(ResultCode.success.getStatusCode(),ResultCode.success.getMsg(),rs);
        }else{
            jsonObject=result.responseResult(ResultCode.exception.getStatusCode(),ResultCode.exception.getMsg());
        }
        return jsonObject;
}

    @Override
    public List<User> getUserList(User user) {
        List<User> userList = userMapper.getUserList(user);
        for (int i = 0; i < userList.size(); i++) {
            List<Plantation> plantations = new ArrayList<>();
            User user1 = userList.get(i);
            List<String> plantationIds = userMapper.getUserRelationByUserId(user1.getUserId());
            for (int j = 0; j < plantationIds.size(); j++) {
                Plantation plantation = plantMapper.getPlantationNameById(plantationIds.get(j));
                plantations.add(plantation);
            }
            userList.get(i).setPlantations(plantations);
        }
        return userList;
    }

    @Override
    public int addUser(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        // 第一步 将管理员所对应的大棚管理加入到关系表当中
        for (int i = 0; i < user.getPlantationIds().size(); i++) {
            UserRelation userRelation = new UserRelation();
            userRelation.setRelationId(UUIDUtil.randomUUID());
            userRelation.setUserId(user.getUserId());
            userRelation.setPlantationId(user.getPlantationIds().get(i));
            int j = userMapper.addUserRelation(userRelation);
        }
        // 第二步 将管理员信息添加进user表中
        user.setPassword(MD5Util.getEncryptedPwd("123456"));
        user.setUserId(UUIDUtil.randomUUID());
        user.setCreatTime(DateUtils.getDate());
        return userMapper.register(user);
    }


}
